'''
Description: Log处理器模块
Author: HowsenFisher
Date: 2021-04-08 22:34:03
LastEditTime: 2021-04-11 10:25:17
LastEditors: liutq
Reference: 
'''
import os
from NetTools.FileRequester import FileRequester
from Config import conf
import shutil

class LogDealer:
    '''
    @description: log处理器类
    @param  {*}
    @return {*}
    @param {*} self
    @param {*} parent：父对象
    @param {*} logfilepath：log文件路径
    '''
    def __init__(self,parent,logfilepath):
        # 父对象
        self.parent = parent
        # 打印info
        self.parent.newInfoSignal.emit("同步脚本处理器初始化")
        # 打开log文件
        self.logfile = open(logfilepath,"r",encoding="utf-8")
        
    '''
    @description: Log处理函数
    @param  {*}
    @return {*}
    @param {*} self
    '''
    def Deal(self):
        # 打印info
        self.parent.newInfoSignal.emit("开始处理同步脚本")
        # 获取log所有的行
        lines = self.logfile.readlines()
        # 遍历行，限制性这段是因为先要创建文件夹以保证目录结构
        for line in lines:
            # 如果行含有mkdir则是创建文件夹命令
            if 'mkdir' in line:
                # 获取文件夹路径
                filepath = line.split(" ")[1].replace("\n","")
                # 创建文件夹
                os.makedirs(filepath)

        # 遍历行
        for line in lines:
            # 获取指令
            order = line.split(" ")[0]
            # 获取文件路径
            filepath = line.split(" ")[1].replace("\n","")
            # 若指令是pull
            if order == 'pull':
                # 获取目标ip
                dst_ip = line.split(" ")[3][:-1]
                # 创建文件请求器
                myFileRequester = FileRequester(self.parent,dst_ip,filepath)
            # 若指令是delete
            elif order == 'delete':
                self.parent.FolderWatcherStop = True
                # 尝试删除文件或文件夹
                try:
                    os.remove(filepath)
                    
                except OSError:
                    pass
                try:
                    shutil.rmtree(filepath)
                except OSError:
                    pass
        # 打印info
        self.parent.newInfoSignal.emit("同步脚本执行完毕")
